package ru.amse.tsyganov.jumleditor.commands;

import ru.amse.tsyganov.jumleditor.model.ActivityGraph;
import ru.amse.tsyganov.jumleditor.model.State;
import ru.amse.tsyganov.jumleditor.model.Transition;
import ru.amse.tsyganov.jumleditor.view.repr.ActivityGraphView;
import ru.amse.tsyganov.jumleditor.view.repr.StateView;

/*package*/ class DeleteStateCommand extends Command {
	
	private final ActivityGraphView<? extends ActivityGraph> activityGraphView;
	
	private final StateView<? extends State> stateView;
	
	private final State state;
	
	public DeleteStateCommand(
			ActivityGraphView<? extends ActivityGraph> activityGraphView,
			StateView<? extends State> stateView) {
		
		if (activityGraphView == null || stateView == null) {
			throw new IllegalArgumentException();
		}
		
		this.activityGraphView = activityGraphView;
		this.stateView = stateView;
		this.state = stateView.getModel();
	}
	
	@Override
	public void execute() {
		
		activityGraphView.getModelViewMap().
			getStatesMap().remove(state);
		
		activityGraphView.getSelectedItems().
			selectedStatesRemove(stateView);
		
		ActivityGraph activityGraph = activityGraphView.getModel();
		
		activityGraph.removeState(state);
		
		for (Transition t : state.getStateVertex().getIncoming()) {
			t.getSource().removeOutgoingTransition(t);
		}
		
		for (Transition t : state.getStateVertex().getOutgoing()) {
			t.getTarget().removeIncomingTransition(t);
		}
	}

	@Override
	public void unexecute() {
		
		activityGraphView.getModelViewMap().getStatesMap().put(state, stateView);
		
		activityGraphView.getModel().addState(state);
		
		for (Transition t : state.getStateVertex().getIncoming()) {
			t.getSource().addOutgoingTransition(t);
		}
		
		for (Transition t : state.getStateVertex().getOutgoing()) {
			t.getTarget().addIncomingTransition(t);
		}
	}
}
